package servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dto.DataManager;

import model.User;

/**
 * Servlet implementation class AddUser
 */
@WebServlet("/AddUser")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataManager dataManager = new DataManager();
		User user = dataManager.getUserWithUserName(request.getParameter("username"));
		if(user == null){
			user = new User();
			Date date =new Date();
			user.setUsername(request.getParameter("username"));
			user.setPassword(request.getParameter("password"));
			user.setBrithDay(request.getParameter("birthday"));
			user.setEmail(request.getParameter("email"));
			user.setDatetimeRegister(date.toString());
			user.setOwnMoney(0);
			user.setRoleId(1);
			if(dataManager.insertUser(user)){
				response.sendRedirect("addUserForm.jsp?isOk=ok");
			}
			else {
				response.sendRedirect("addUserForm.jsp?isOk=no");
					}
		}
		else response.sendRedirect("addUserForm.jsp?isOk=used");

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
